require 'RMagick'
include Magick

class Picture < ActiveRecord::Base
  has_many :galleries
  has_many :ads, :through => :galleries
  has_many :picture_owners
  has_many :users, :through => :picture_owners

  def self.resize_and_create(file)
    id = Digest::MD5.hexdigest(file.read)

    #only resize and store if it is not allready stored
    begin
      Picture.find id
    rescue
      img = Magick::Image.read(file.path).first

      store = Picture.new
      large = img.resize_to_fit(1000,1000)
      store.large = large.to_blob
      store.id=(id)

      begin
        store.save
      rescue ActiveRecord::StatementInvalid
      end
    end

    id
  end
  
  def self.assign_to_user(user_id,picture_id)
    unless PictureOwner.find_by_user_id_and_picture_id(user_id,picture_id)
      PictureOwner.create(:user_id => user_id, :picture_id => picture_id)
    end
  end

  def to_param
    "#{id}.jpg"
  end


  def self.resize(id,size=0)
    img = Magick::Image.from_blob(Picture.find_by_id(id).large).first
    unless size == 0
      img = img.resize_to_fit(size,size)
    end
    img
  end
end
